package com.example.administrator.design.ui.main.fragment;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.design.R;
import com.example.administrator.design.base.mvpbase.baseImpl.BaseFragment;
import com.example.administrator.design.bean.TripListBean;
import com.example.administrator.design.ui.login.activity.LoginActivity;
import com.example.administrator.design.ui.main.TripDetailsActivity;
import com.example.administrator.design.ui.main.activity.AddTripActivity;
import com.example.administrator.design.ui.main.activity.SearchActivity;
import com.example.administrator.design.ui.main.adapter.TripListAdapter;
import com.example.administrator.design.ui.main.contacts.TripListContacts;
import com.example.administrator.design.ui.main.presenter.TripListPresenter;
import com.example.administrator.design.utils.ActivityManager;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.orhanobut.hawk.Hawk;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TripFragment extends BaseFragment<TripListContacts.presenter> implements
            TripListContacts.view{

    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;
    @BindView(R.id.rv_trip_list)
    RecyclerView rvTripList;
    @BindView(R.id.refreshLayout)
    TwinklingRefreshLayout refreshLayout;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.tv_add)
    TextView tvAdd;

    private List<TripListBean.TravelPlanListBean> list_path = new ArrayList<>();
    private TripListAdapter listAdapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_tripragment;
    }

    @Override
    protected void initView() {
         presenter.tripList();
        ProgressLayout headView = new ProgressLayout(getContext());
        headView.setColorSchemeColors(ContextCompat.getColor(getContext(), R.color.colorAccent), ContextCompat.getColor(getContext(), R.color.yellow),
                ContextCompat.getColor(getContext(), R.color.Green));
        refreshLayout.setHeaderView(headView);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                 presenter.onRefresh();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                new Handler().postDelayed(() -> refreshLayout.finishLoadmore(), 1500);
            }
        });

//        rvTripList.setOnScrollListener(new RecyclerView.OnScrollListener() {
//            //用来标记是否正在向最后一个滑动
//            boolean isSlidingToLast = false;
//
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                //设置什么布局管理器,就获取什么的布局管理器
//                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                // 当停止滑动时
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    //获取最后一个完全显示的ItemPosition ,角标值
//                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
//                    //所有条目,数量值
//                    int totalItemCount = manager.getItemCount();
//
//                    // 判断是否滚动到底部，并且是向右滚动
//                    if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
//                        ivAdd.setVisibility(View.VISIBLE);
//                    }else {
//                        ivAdd.setVisibility(View.GONE);
//                    }
//                }
//            }

//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
//                //dx>0:向右滑动,dx<0:向左滑动
//                //dy>0:向下滑动,dy<0:向上滑动
//                if (dy > 0) {
//                    isSlidingToLast = true;
//                } else {
//                    isSlidingToLast = false;
//                }
//            }
//        });
        rvTripList.setLayoutManager(new LinearLayoutManager(getContext()));
        listAdapter = new TripListAdapter(list_path);
        rvTripList.setAdapter(listAdapter);
        /**
         *  加入行程点击事件
         */
        listAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                TextView tvJoin=view.findViewById(R.id.tvJoin);
                if (view.getId() == R.id.rl_add) {
                    if(tvJoin.getText().toString().trim().equals("join")){
                        presenter.joinTrip(listAdapter.getItem(position).getPlanId());
                        tvJoin.setText("Nojoin");
                    }else {
                        presenter.NojoinTrip(listAdapter.getItem(position).getPlanId());
                        tvJoin.setText("join");
                    }

                }
            }
        });

        /**
         *  行程详情点击事件
         */
        listAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(getContext(),TripDetailsActivity.class)
                .putExtra("planId",listAdapter.getItem(position).getPlanId())
                .putExtra("title",listAdapter.getItem(position).getPlanName())
                .putExtra("time",listAdapter.getItem(position).getTime()));
            }
        });
    }

    @Override
    public TripListContacts.presenter initPresenter() {
        return new TripListPresenter(this);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @OnClick({R.id.iv_search, R.id.tv_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_search:
                startActivity(new Intent(getContext(), SearchActivity.class));
                break;
            case R.id.tv_add:
                startActivity(new Intent(getContext(), AddTripActivity.class));
                break;
        }
    }

    @Override
    public String getToken() {
        return Hawk.get("token").toString();
    }


    @Override
    public void LoadData(List<TripListBean.TravelPlanListBean> travelPlanList) {
        listAdapter.setNewData(travelPlanList);
    }

    @Override
    public String getDataFlag() {
        return "1";
    }

    @Override
    public void Success() {
        ToastUtils.showShort("加入行程成功");
    }

    @Override
    public void finishRefresh() {
        new Handler().postDelayed(() ->  refreshLayout.finishRefreshing(), 1000);

    }

    @Override
    public void CancelSuccess() {
        ToastUtils.showShort("已经取消行程");
    }

    @Override
    public void againLogin() {
        startActivity(new Intent(getContext(), LoginActivity.class));
        ActivityManager.getAppInstance().finishAllActivity();
    }
}
